//
//  SJComposeViewController.swift
//  SJWeiboSwift
//
//  Created by app;e on 15/10/14.
//  Copyright © 2015年 world. All rights reserved.
//

import UIKit
import SVProgressHUD

//微博的最大长度
private let statusMaxLength = 140

class SJComposeViewController: UIViewController,UITextViewDelegate {
    ///表情键盘控制器
    // [unowned self] 对self不做强引用
    private lazy var emotionKeyBoardVC:SJEmoticonViewController = SJEmoticonViewController { [unowned self](emotion) -> () in
        self.textView.insertEmoticon(emotion)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        textView.resignFirstResponder()

    }
    
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        
        //添加表情键盘控制器
        addChildViewController(emotionKeyBoardVC)
        
        prepareNavigationBar()
        prepareToolBar()
        prepareTextView()
        prepareForOthers()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //添加键盘改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardFrameChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }

    
    ///析构方法,移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    ///通知的回掉方法
    private var isCloseKeyBoardFlag = false
    func keyBoardFrameChange(notific:NSNotification){
        
//        print(notific)
        //键盘移动的最终位置
        let endRect = notific.userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue
        //计算toolBar的y方向偏移量
        let offSet = -(view.frame.size.height - endRect!.origin.y)
//        print(offSet)
        toolBarBottomConstrain?.constant = offSet
        //动画时间
        var  duration = notific.userInfo![UIKeyboardAnimationDurationUserInfoKey]?.doubleValue
        
        //弹出的时候,UIKeyboardFrameEndUserInfoKey 的y值是409,451 .
        //键盘退出的时候,最终都回到屏幕最地步  也就是退出的时候为667
        //点击表情键盘的时候会有抖动的效果, 是因为 我们在inputEmoticon切换表情键盘的时候 先关闭退出系统键盘, 在 设置表情键盘为当前第一响应者. 所以会出现抖动 为来解决这个问题. 当UIKeyboardFrameEndUserInfoKey为 屏幕的高度也就是退出的时候 不进行动画
//        print("\(endRect?.origin.y)+\(UIScreen.mainScreen().bounds.height)")
        
        if endRect?.origin.y == UIScreen.mainScreen().bounds.height {
            isCloseKeyBoardFlag = true
            return
        }
        //关闭键盘 动画时间为0, 开启键盘动画时间 为duration
        duration = isCloseKeyBoardFlag ? 0 : duration
        
        UIView.animateWithDuration(duration!) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    ///切换表情视图
    func inputEmoticon(){
        //切换键盘之前 先关闭 系统键盘  这个时候textView的inputView为nil
        textView.resignFirstResponder()
        
        //更换键盘输入视图
        textView.inputView = (textView.inputView == nil) ? emotionKeyBoardVC.view : nil
        
        //重新设置第一响应者
        textView.becomeFirstResponder()
    }
    
    ///发送
    func sendStatus(){
        //判断textView是否有值
        if (textView.emoticonText() as NSString).length <= 0{
            return
        }
        if (textView.emoticonText() as NSString).length > statusMaxLength {
            SVProgressHUD.showInfoWithStatus("您输入的字符已经超过最大限制", maskType: SVProgressHUDMaskType.Black)
            return
        }
        //发送中
        SVProgressHUD.show()
        SJNetWorkTools.sharedNetWorkTools().postStauts(textView.emoticonText()) { (error) -> () in
            if error != nil{
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            }
            //发布成功
            self.close()
        }
    }
    
    ///取消发送
    func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: -textView的代理
    func textViewDidChange(textView: UITextView) {
        print(textView)
        placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        let textLength = statusMaxLength - (textView.emoticonText() as NSString).length
        
        lengthLabel.textColor = textLength > 0 ? UIColor.lightGrayColor() : UIColor.redColor()
        lengthLabel.text = textLength == 0 ? "" : String(textLength)
    }
    
    //MARK: - 准备UI
    ///准备其他
    private func prepareForOthers(){
        view.addSubview(lengthLabel)
        
        lengthLabel.ff_AlignInner(ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -12, y: -12))
    }
    
    ///准备工具条
    private func prepareToolBar(){
        toolBar.frame = CGRectMake(0, 0, 0, 44)
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        //存放字典的数组 , 一个字典对应一个UIBarButtonItem 初始化 的值
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]

        //遍历数组创建UIBarButtonItem
        //创建数组 存放创建完的UIBarButtonItem
        var items = [UIBarButtonItem]()
        for setting in itemSettings {
            let item = UIBarButtonItem(imageName: setting["imageName"]!, hlightedImageName: nil, trag: nil, actionName: setting["action"])
            items.append(item)
            
            //创建弹簧
            let th = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            items.append(th)
        }
        //删除最后一个弹簧
        items.removeLast()
        //赋值给toolBar的items
        toolBar.items = items
        
        //将工具条添加到当前控制器的view
        view.addSubview(toolBar)
        //设置约束
        let cons = toolBar.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: nil)
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["toolBar":toolBar]))
        //获取toolBar底部的约束
        toolBarBottomConstrain = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
    }
    
   
    
    ///准备textView
    private func prepareTextView(){
        view.addSubview(textView)
        textView.backgroundColor = UIColor.whiteColor()
        textView.font = UIFont.systemFontOfSize(15)
//        textView.inputAccessoryView = prepareToolBar()
        
//        textView.ff_Fill(view)
        //textView的布局
        //使用topleft这种布局模式,会让textView从左上角开始,开始输入的文字会被状态栏与导航栏挡住
        //解决办法有2种,第一种在布局中设置offset,这样让textView从64开始,这样设置的坏处是textView不能在滚到导航栏下面,不会在有穿透效果
        //第二种方式:textView的size照常设置, 在设置完以后通过设置textView的contentInset
        textView.ff_AlignInner(ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(ff_AlignType.TopRight, referView: toolBar, size: nil)
        textView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0)
        
        textView.alwaysBounceVertical = true
        textView.delegate = self
        
        //滚动关闭键盘
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        //添加默认文字
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.text = "分享新鲜事..."
        placeHolderLabel.sizeToFit()
        placeHolderLabel.ff_AlignInner(ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))

    }
    
    
    ///准备导航栏
    private func prepareNavigationBar(){
        //左侧导航栏
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Done, target: self, action: "close")
        //右侧导航栏
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Done, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        //titleView
        let titleView = UIView()
        let label1 = UILabel(color: UIColor.darkGrayColor(), textSize: UIFont.systemFontOfSize(15), mutableLines: false)
        label1.text = "发微博"
        let label2 = UILabel(color: UIColor(white: 0, alpha: 0.5), textSize: UIFont.systemFontOfSize(12), mutableLines: false)
        label2.text = sharedUserAccount?.name ?? ""
        titleView.addSubview(label1)
        titleView.addSubview(label2)
        label1.ff_AlignInner(ff_AlignType.BottomCenter, referView: titleView, size: nil)
        label2.ff_AlignInner(ff_AlignType.TopCenter, referView: titleView, size: nil)
        navigationItem.titleView = titleView
    }
    
    //MARK: - 懒加载
    lazy var textView = UITextView()
    lazy var toolBar = UIToolbar(frame: CGRectMake(0, 0, 0, 44))
    lazy var placeHolderLabel = UILabel(color: UIColor(white: 0.8, alpha: 1), textSize: UIFont.systemFontOfSize(15), mutableLines: false)
    lazy var lengthLabel = UILabel(color: UIColor.lightGrayColor(), textSize: UIFont.systemFontOfSize(12), mutableLines: false)
    ///toolBar底部的约束
    private var toolBarBottomConstrain : NSLayoutConstraint?
}
